package com.kefu.chat.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.kefu.call.model.CallMakeCall;
import com.kefu.chat.mapper.ChatSessionMapper;
import com.kefu.chat.model.ChatSession;
import com.kefu.chat.vo.ChatSkillsetsWorkLoadVo;
import com.kefu.chat.vo.ChatSkillsetsWorkloadSearchVo;
import com.kefu.common.context.KefuContext;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.common.util.BigDecimalUtil;
import com.kefu.sys.mapper.SysGroupMapper;
import com.kefu.sys.model.SysGroup;
import com.kefu.sys.model.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kefu.chat.model.ChatAdmin;
import com.kefu.chat.vo.ChatRealTimeData;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@Service
public class ChatReportService extends AbstractKefuService<ChatSession> {
    @Resource
    private SysGroupMapper sysGroupMapper;
    @Autowired
    private ChatCacheService chatCacheService;
    @Resource
    private ChatSessionMapper chatSessionMapper;

    public ChatRealTimeData getRealTimeData(String tenantId) {
        ChatRealTimeData data = new ChatRealTimeData();
        data.setRobotCount(chatCacheService.getRobotSetSize(tenantId));
        data.setWaitCount(chatCacheService.getWaitSize(tenantId));
        data.setAgentCount(chatCacheService.getAdminSetSize(tenantId));
        Set<String> adminIds = chatCacheService.getAdminSet(tenantId);
        long onlineCount = 0;
        for (String adminId : adminIds) {
            ChatAdmin admin = chatCacheService.getAdmin(adminId);
            long currentAccept = chatCacheService.getAdminUserSetSize(adminId);
            admin.setCurrentAccept(currentAccept);
            onlineCount = onlineCount + currentAccept;
            if (admin.getStatusTime() != 0) {
                admin.setStatusDuration(System.currentTimeMillis() - admin.getStatusTime() / 1000);
            }
            data.getAgentList().add(admin);
        }
        data.setOnlineCount(onlineCount);
        return data;
    }

    public List<ChatSkillsetsWorkLoadVo> chatSkillsetsWorkloadList(ChatSkillsetsWorkloadSearchVo param) {
        List<ChatSkillsetsWorkLoadVo> workList = Lists.newArrayList();
        Map<String, Object> staticQuery = Maps.newHashMap();
        staticQuery.put("startTime", param.getQueryTimeStart());
        staticQuery.put("endTime", param.getQueryTimeEnd());
        staticQuery.put("tenantId", KefuContext.getTid());
        if (StrUtil.isNotBlank(param.getGroupId())) {
            staticQuery.put("groupId", param.getGroupId());
        }
        List<Map<String, Object>> overviewSkillsets = chatSessionMapper.staticsSkillsetsChatList(staticQuery);
        List<SysGroup> sysGroups = sysGroupMapper.selectList(Wrappers.lambdaQuery(SysGroup.class)
                .eq(SysGroup::getTenantId, KefuContext.getTid())
                .eq(SysGroup::getGroupType, 0));
        Map<String, String> groupMap = sysGroups.stream().collect(Collectors.toMap(SysGroup::getGroupId, SysGroup::getGroupName));
        overviewSkillsets.forEach(chat -> {
            BigDecimal tranferNumber = BigDecimalUtil.get(chat.get("tranfernumber"));
            BigDecimal replyNumber = BigDecimalUtil.get(chat.get("replynumber"));
            BigDecimal totalNumber = BigDecimalUtil.get(chat.get("totalnumber"));
            BigDecimal finishChatNumber = BigDecimalUtil.get(chat.get("finishchatnumber"));
            BigDecimal avgTotalTime = BigDecimalUtil.get(chat.get("avgtotaltime"));
            BigDecimal avgReplyDuration = BigDecimalUtil.get(chat.get("avgreplyduration"));
            ChatSkillsetsWorkLoadVo workLoadVo = new ChatSkillsetsWorkLoadVo();
            workLoadVo.setTransferNumber(tranferNumber.intValue());
            workLoadVo.setReplyNumber(replyNumber.intValue());
            workLoadVo.setTotalNumber(totalNumber.intValue());
            workLoadVo.setFinishChatNumber(finishChatNumber.intValue());
            workLoadVo.setAvgTotalTime(avgTotalTime.intValue());
            workLoadVo.setAvgReplyDuration(avgReplyDuration.intValue());
            if (chat.get("groupid") != null) {
                workLoadVo.setGroupId(chat.get("groupid").toString());
                workLoadVo.setGroupName(groupMap.get(workLoadVo.getGroupId()));
                workList.add(workLoadVo);
            }
        });
        return workList;
    }

    public void exportChatSkillsetsWorkload(ChatSkillsetsWorkloadSearchVo param, HttpServletResponse response) throws IOException {
        List<Object[]> exportList = new ArrayList<>();
        Object[] title = {msg("技能组id"), msg("技能组"),
                msg("回复消息数"), msg("转接数"),
                msg("接入坐席会话数"), msg("完成会话数"),
                msg("平均会话时长(秒)"), msg("平均首次响应时长(秒)")
        };
        exportList.add(title);
        List<ChatSkillsetsWorkLoadVo> list = chatSkillsetsWorkloadList(param);
        list.forEach(work -> {
            Object[] row = {work.getGroupId(), work.getGroupName(),
                    work.getReplyNumber(), work.getTransferNumber(),
                    work.getTotalNumber(), work.getFinishChatNumber(),
                    work.getAvgTotalTime(), work.getAvgReplyDuration()
            };
            exportList.add(row);
        });
        csvWriter(exportList, response);
    }
}
